package cac.fenjian.resource.finProReceiveSearch.rest;

import cac.common.CallInterFace.service.CallInterfaceService;
import cac.fenjian.resource.WmsDeliverPlan.dto.WmsDeliverPlanDTO;
import cac.fenjian.resource.finProReceiveSearch.service.FinProReceiveSearchService;
import cac.fenjian.resource.partreceivesearch.dao.PartReceiveDao;
import cac.fenjian.resource.partreceivesearch.service.PartReceiveService;
import cac.fenjian.resource.tsuser.service.TsUserServiceImpl;
import com.alibaba.fastjson.JSON;
import com.cac.dme.adapter.rest.msg.PageParameter;
import com.cac.dme.adapter.rest.msg.QueryReqBean;
import com.cac.dme.adapter.rest.msg.QueryRespBean;
import com.cac.dme.adapter.rest.msg.ResponseMsg;
import com.cac.dme.adapter.utils.ContextCommonHolder;
import com.cac.dme.common.utils.JsonHelper;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.cac.dme.adapter.utils.BusinessUtil.getSortExpColumnName;

@RestController
@RequestMapping("/finProReceiveSearch")
@Slf4j
public class FinProReceiveSearchRest {

    @Autowired
    private FinProReceiveSearchService finProReceiveSearchService;
    @Autowired
    private PartReceiveDao partReceiveDao;
    @Autowired
    private CallInterfaceService callInterfaceService;
    @Autowired
    private TransactionDefinition transactionDefinition;
    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private PartReceiveService partReceiveService;
    @Autowired
    private TsUserServiceImpl tsUserService;


    //零件接收页面条件查询
    @PostMapping("/searchParamsByItemFS")
    public ResponseMsg<QueryRespBean<WmsDeliverPlanDTO>> searchParamsByItemFS(@RequestBody Map map) {
        ResponseMsg<QueryRespBean<WmsDeliverPlanDTO>> responseMsg = new ResponseMsg<>();
        //获取图号
        String itemCode = (String) map.get("itemCode");
        //时间范围
        String startTimeParams = JSON.toJSONString(map.get("startTime"));
        String endTimeParams = JSON.toJSONString(map.get("endTime"));
        Date startTime = JSON.parseObject(startTimeParams, Date.class);
        Date endTime = JSON.parseObject(endTimeParams, Date.class);
        //分页
        String param = JSON.toJSONString(map.get("pageParameter"));
        PageParameter pageParameter = JSON.parseObject(param, PageParameter.class);
        //查询条件
        String searchParamsParams = JSON.toJSONString(map.get("searchParams"));
        WmsDeliverPlanDTO searchParams = JSON.parseObject(searchParamsParams, WmsDeliverPlanDTO.class);

        QueryReqBean<WmsDeliverPlanDTO> queryReqBean = new QueryReqBean<>();
        queryReqBean.setSearchParams(searchParams);
        queryReqBean.setPageParameter(pageParameter);

        if (StringUtils.hasText(queryReqBean.getSidx()) && StringUtils.hasText(queryReqBean.getSord())) {
            String sordExp = getSortExpColumnName(queryReqBean.getSidx(), queryReqBean.getSord(), WmsDeliverPlanDTO.class);
            if (StringUtils.hasText(sordExp)) {
                queryReqBean.setSortExp(sordExp);
            }
        }
        if (StringUtils.hasText(queryReqBean.getKeyWord())) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            WmsDeliverPlanDTO searchKeyWordParam = JsonHelper.getInstance().readValue(queryReqBean.getKeyWord(), dateFormat, new TypeReference<WmsDeliverPlanDTO>() {
            });
            queryReqBean.setSearchParams(searchKeyWordParam);
        }

        QueryRespBean<WmsDeliverPlanDTO> result = finProReceiveSearchService.searchParamsByItemFS(queryReqBean, ContextCommonHolder.getOrgId(), queryReqBean.getSortExp(), startTime, endTime, itemCode);
        responseMsg.setResponseBody(result);
        return responseMsg;
    }

    //C成品接收条码查询
    @PostMapping("/searchByBarcode")
    public ResponseMsg<QueryRespBean<List<HashMap>>> searchByBarcodeFS(@RequestBody Map map) {
        ResponseMsg<QueryRespBean<List<HashMap>>> responseMsg = new ResponseMsg<>();
        //获取条码
        String barcode = (String) map.get("barcode");
        //分页
        String param = JSON.toJSONString(map.get("pageParameter"));
        PageParameter pageParameter = JSON.parseObject(param, PageParameter.class);
        //查询条件
        String searchParamsParams = JSON.toJSONString(map.get("searchParams"));
        HashMap searchParams = JSON.parseObject(searchParamsParams, HashMap.class);
        QueryReqBean<HashMap> queryReqBean = new QueryReqBean<>();
        queryReqBean.setSearchParams(searchParams);
        queryReqBean.setPageParameter(pageParameter);
        if (StringUtils.hasText(queryReqBean.getSidx()) && StringUtils.hasText(queryReqBean.getSord())) {
            String sordExp = getSortExpColumnName(queryReqBean.getSidx(), queryReqBean.getSord(), WmsDeliverPlanDTO.class);
            if (StringUtils.hasText(sordExp)) {
                queryReqBean.setSortExp(sordExp);
            }
        }
        if (StringUtils.hasText(queryReqBean.getKeyWord())) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            HashMap searchKeyWordParam = JsonHelper.getInstance().readValue(queryReqBean.getKeyWord(), dateFormat, new TypeReference<HashMap>() {
            });
            queryReqBean.setSearchParams(searchKeyWordParam);
        }
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String account = (String) request.getSession().getAttribute("account");
        if (Objects.isNull(account)) {
            log.info("session过期，请重新登陆");
            responseMsg.setMessage("账户已过期，请重新登录").setRetCode("201");
            return responseMsg;
        } else if ("admin".equals(account)) {
            return responseMsg.setRetCode("201").setErrorDesc("管理员账号无法完成操作，请切换登录用户");
        }
        String shop = (String)tsUserService.getUserInfoByAccount(account).get("shop");

        if(finProReceiveSearchService.queryCpHgzIsRepeat(barcode,shop)){
            return responseMsg.setRetCode("201").setMessage("当前条码重复，"+barcode+"条码在”"+shop+"“，存在合格证号一样的数据，请确认");
        }

        //2023-08-18 yebo 判断是否需要直配
        if(map.containsKey("sendType")){
            if("Y".equals(map.get("sendType"))){
                //判断是否需要直配
                List<HashMap> rsl=partReceiveDao.searchIsDirect(barcode);
                if(rsl.size()>0){
                    return responseMsg.setMessage("当前条码："+barcode+"，存在日计划未配送，请到接收直配页面进行直配操作！").setRetCode("201");
                }
            }
        }

        QueryRespBean<List<HashMap>> result = finProReceiveSearchService.searchParamsByBarcodeFS(queryReqBean, ContextCommonHolder.getOrgId(), queryReqBean.getSortExp(), barcode,shop);
        //判断该物料是否为大件物料
        List<HashMap> isBig = partReceiveService.isBig(barcode);
        List<HashMap> isWork = finProReceiveSearchService.boolResult(barcode);
        if (isWork.size() == 0 || isWork.isEmpty()) {
            // isWork.get("")
            responseMsg.setRetCode("201").setMessage("当前交接单未移交或者已入库，或所属单位与当前操作人不同！");
        }else {
            if (!Objects.isNull(isBig)) {
                responseMsg.setMessage("扫码成功！").setRetCode("200");
            } else {
                responseMsg.setMessage("大件物料扫码成功！").setRetCode("200");
            }
            responseMsg.setResponseBody(result);
        }
        return responseMsg;
    }

    //改变接收状态
    @PostMapping("/changeAccType")
    public ResponseMsg<String> changeTransferType(@RequestBody Map map) throws ParseException {
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        String barcode = (String) map.get("barcode");
        String wmsDeliveryPlanId = (String) map.get("wmsDeliveryPlanId");
        //List<String> barcodes = (List<String>) map.get("barcode");
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        String receiveEmpCode = (String) request.getSession().getAttribute("account");
        if (Objects.isNull(receiveEmpCode)) {
            responseMsg.setRetCode("201");
            responseMsg.setMessage("登录过期，请重新登录！").setErrorDesc("登录过期，请重新登录！");
            return responseMsg;
        }else if ("admin".equals(receiveEmpCode)){
            return  responseMsg.setRetCode("201").setMessage("管理员账号无法完成操作，请切换登录用户").setErrorDesc("管理员账号无法完成操作，请切换登录用户");
        }
        log.info("IP" + IP);
        String result = finProReceiveSearchService.changeMaterialSate(barcode, receiveEmpCode, IP,wmsDeliveryPlanId);
        if (result.equals("OK")) {
            responseMsg.setRetCode("200");
            responseMsg.setMessage("操作成功！");
        } else if (result.equals("IllegalBarcode")) {
            responseMsg.setRetCode("201").setErrorDesc("条码数据有误！");
        }
        return responseMsg;
    }

//        //批量接收
//        @PostMapping("/changeAccTypes")
//        public ResponseMsg<String> changeTransferTypes (@RequestBody Map map) throws ParseException {
//            ResponseMsg<String> responseMsg = new ResponseMsg<>();
//            List<String> barcodes = (List<String>) map.get("barcode");
//            String receiveEmpCode = (String) map.get("receiveEmpCode");
//            String IP = null;
//            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//            if (request.getHeader("x-forwarded-for") == null) {
//                IP = request.getRemoteAddr();
//            } else {
//                IP = request.getHeader("x-forwarded-for");
//            }
//            log.info("IP" + IP);
//            String result = finProReceiveSearchService.changeMaterialSates(barcodes, receiveEmpCode, IP);
//            if (result.equals("OK")) {
//                responseMsg.setRetCode("200");
//                responseMsg.setMessage("操作成功！");
//            } else if (result.equals("IllegalBarcode")) {
//                responseMsg.setRetCode("201");
//                responseMsg.setErrorDesc("条码不存在！");
//            } else if (result.equals("IllegalStatu")) {
//                responseMsg.setRetCode("201");
//                responseMsg.setErrorDesc("条码状态错误！");
//            }
//            return responseMsg;
//        }
}
